package com.quectel.cms.controller.scheduling;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.scheduling.SchedulingLeaveInitReq;
import com.quectel.constant.core.scheduling.SchedulingLeaveConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.dept.dto.DeptDto;
import com.quectel.core.module.dept.service.DeptService;
import com.quectel.core.module.scheduling.dto.SchedulingLeaveConfigDto;
import com.quectel.core.module.scheduling.service.SchedulingLeaveConfigService;
import com.quectel.core.module.scheduling.service.SchedulingLeavePersonBindingService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/05 13:24
 */
@RestController
@RequestMapping("schedulingLeaveConfig")
@Tag(name = "SchedulingLeaveConfigController", description = "考勤假期配置相关api")
public class SchedulingLeaveConfigController extends BaseController {

    @DubboReference
    private SchedulingLeaveConfigService schedulingLeaveConfigService;
    @DubboReference
    private SchedulingLeavePersonBindingService schedulingLeavePersonBindingService;
    @DubboReference
    private DeptService deptService;
    @DubboReference
    private VillageService villageService;


    /**
     * 初始化假期
     *
     * @param req
     * @return
     */
    @PostMapping("initLeave")
    @RequirePermissions(values = "schedulingLeaveConfig:edit")
    @Operation(summary = "新增考勤假期配置")
    public Response<Object> initLeave(@RequestBody @Validated SchedulingLeaveInitReq req) {

        List<Byte> typeList = req.getTypeList();
        if (CollectionUtils.isEmpty(typeList)) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        Long villageId = req.getVillageId();
        if (villageId == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        VillageDto villageDto = villageService.selectCacheById(villageId);
        if (villageDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        for (Byte leaveType : typeList) {
            //查询假期类型 如果存在则跳过

            List<SchedulingLeaveConfigDto> schedulingLeaveConfigDtos = schedulingLeaveConfigService.selectByVillageAndType(villageId, leaveType);

            if (CollectionUtils.isNotEmpty(schedulingLeaveConfigDtos)) {
                continue;
            }

            SchedulingLeaveConstants.LeaveTypeEnum byType = SchedulingLeaveConstants.LeaveTypeEnum.getByType(leaveType);
            if (byType == null) {
                continue;
            }

            SchedulingLeaveConfigDto schedulingLeaveConfigDto = JacksonUtils.parse(byType.getTemplate(), SchedulingLeaveConfigDto.class);
            schedulingLeaveConfigDto.setStatus(SystemConstants.NO);
            schedulingLeaveConfigDto.setVillageId(villageId);
            schedulingLeaveConfigDto.setGrantRuleJson(JacksonUtils.toJsonString(schedulingLeaveConfigDto.getGrantRule()));
            schedulingLeaveConfigDto.setUsageRuleJson(JacksonUtils.toJsonString(schedulingLeaveConfigDto.getUsageRule()));
            //填充基础数据
            fillSaveCommonData(schedulingLeaveConfigDto);

            schedulingLeaveConfigService.save(schedulingLeaveConfigDto);

        }

        return Response.ok();
    }

    /**
     * 查询限额假期列表
     *
     * @return
     */
    @GetMapping("limitLeaveList")
    @RequirePermissions(values = "schedulingLeaveBalance:list")
    @Operation(summary = "查询限额假期列表")
    public Response<List<SchedulingLeaveConfigDto>> limitLeaveList(
            @Parameter(description = "小区id") @RequestParam(required = false) Long villageId,
            @Parameter(description = "部门id") @RequestParam(required = false) Long deptId,
            @Parameter(description = "是否限额") @RequestParam(required = false) Byte limitFlag
    ) {
        if (villageId == null && deptId == null) {
            return Response.<List<SchedulingLeaveConfigDto>>ok().wrap(Collections.emptyList());
        }
        if (deptId != null) {
            DeptDto deptDto = deptService.selectCacheById(deptId);
            if (deptDto == null) {
                return Response.<List<SchedulingLeaveConfigDto>>ok().wrap(Collections.emptyList());
            }
            villageId = deptDto.getVillageId();
        }

        Map<String, Object> leaveParams = new HashMap<>();
        super.fillAuthorityData(leaveParams);
        leaveParams.put(LambdaUtil.getFieldName(SchedulingLeaveConfigDto::getTenantId), SessionHolder.getSysUser().getTenantId());
        leaveParams.put(LambdaUtil.getFieldName(SchedulingLeaveConfigDto::getVillageId), villageId);
        if (limitFlag != null) {
            leaveParams.put(LambdaUtil.getFieldName(SchedulingLeaveConfigDto::getLimitFlag), SystemConstants.YES);
        }
        leaveParams.put(LambdaUtil.getFieldName(SchedulingLeaveConfigDto::getStatus), SystemConstants.NORMAL);
        List<SchedulingLeaveConfigDto> schedulingLeaveConfigDtos = schedulingLeaveConfigService.queryList(leaveParams);

        if (CollectionUtils.isNotEmpty(schedulingLeaveConfigDtos)){
            for (SchedulingLeaveConfigDto schedulingLeaveConfigDto : schedulingLeaveConfigDtos) {
                schedulingLeaveConfigDto.setTypeName(SysCodeUtils.easyToGetName(SysCodeKeyConstants.SCHEDULING_LEAVE_TYPE, schedulingLeaveConfigDto.getType() + ""));
            }
        }
        return Response.<List<SchedulingLeaveConfigDto>>ok().wrap(schedulingLeaveConfigDtos);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "schedulingLeaveConfig:list")
    @Operation(summary = "分页获取考勤假期配置列表")
    public Response<Page<SchedulingLeaveConfigDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = schedulingLeaveConfigService.queryTotal(request.getParams());

        List<SchedulingLeaveConfigDto> list = null;
        if (total > 0) {
            list = schedulingLeaveConfigService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SchedulingLeaveConfigDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SchedulingLeaveConfigDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "schedulingLeaveConfig:edit")
    @Operation(summary = "在编辑时根据id查询考勤假期配置详情")
    public Response<SchedulingLeaveConfigDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingLeaveConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingLeaveConfigDto schedulingLeaveConfigDto = schedulingLeaveConfigService.selectById(id);

        return Response.<SchedulingLeaveConfigDto>ok().wrap(schedulingLeaveConfigDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "schedulingLeaveConfig:info")
    @Operation(summary = "根据id查询考勤假期配置的详情")
    public Response<SchedulingLeaveConfigDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingLeaveConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingLeaveConfigDto schedulingLeaveConfigDto = schedulingLeaveConfigService.selectById(id);

        return Response.<SchedulingLeaveConfigDto>ok().wrap(schedulingLeaveConfigDto);
    }

    /**
     * 保存
     *
     * @param schedulingLeaveConfigDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "schedulingLeaveConfig:edit")
    @Operation(summary = "新增考勤假期配置")
    public Response<Object> save(@RequestBody @Validated SchedulingLeaveConfigDto schedulingLeaveConfigDto) {

        //填充基础数据
        fillSaveCommonData(schedulingLeaveConfigDto);


        schedulingLeaveConfigService.saveOrUpdate(schedulingLeaveConfigDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param schedulingLeaveConfigDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "schedulingLeaveConfig:edit")
    @Operation(summary = "根据id修改考勤假期配置")
    public Response<Object> update(@RequestBody @Validated SchedulingLeaveConfigDto schedulingLeaveConfigDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(schedulingLeaveConfigDto.getId()));
        if (schedulingLeaveConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(schedulingLeaveConfigDto);

        schedulingLeaveConfigService.saveOrUpdate(schedulingLeaveConfigDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "schedulingLeaveConfig:delete")
    @Operation(summary = "根据多条记录id批量删除考勤假期配置")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (schedulingLeaveConfigService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        schedulingLeaveConfigService.deleteBatch(ids);

        return Response.ok();
    }
}
